<?php
namespace app\admin\controller;
use app\index\model\User as UserModel;
use think\Loader;
use think\Controller;

class User extends Common
{
	/**
	 * 用户列表主页
	 * @return mixed
	 * @throws \think\exception\DbException
	 */
	public function userlist()
	{
		$where = [];
		input('nickname') && $where['nickname'] = ['like','%'.input('nickname').'%'];
		if(input('start') && input('end')){
			$where['create_time'] = [
				['>=',strtotime(input('start'))],
				['<=',strtotime(input('end'))+86400]
			];
		}else if(input('start')){
			$where['create_time'] = ['>=',strtotime(input('start'))];
		}else if(input('end')){
			$where['create_time'] = ['<=',strtotime(input('end'))+86400];
		}
		$users = UserModel::where($where)->paginate(5);
		$this->assign('users',$users);
		return $this->fetch();
	}


	/**
	 * 删除用户
	 */
	public function del()
	{
		$user_id = input('user_id');
		$res = UserModel::destroy($user_id);
		if($res){
			$this->success("删除成功");
		}else{
			$this->error("删除失败");
		}
	}


	/**
	 * 删除所选用户
	 */
	public function delUser(){
		$user_id = input('post.');
		$user_id = implode(',',$user_id['user_id']);
		$res = UserModel::destroy($user_id);
		if ($res){
			$this->success('已删除');
		}else{
			$this->error('删除失败');
		}
	}

	/**
	 * 添加用户主页
	 * @return mixed
	 */
	public function addUser(){
		return $this->fetch();
	}


	/**
	 * 添加用户方法
	 */
	public function addUsers(){
		$post = input('post.');
		$validate = Loader::validate('CheckAddUser');
		if(!$validate->check($post)){
			$this->error($validate->getError());
		}
		$post['create_time'] = time();
		$post['password'] = md5($post['password']);
		$res = UserModel::create($post);
		if ($res){
			$this->success('已添加');
		}else{
			$this->error('添加失败,请稍后在尝试');
		}
	}


	/**
	 *
	 * @return mixed
	 */
	public function edit(){
		return $this->fetch();
	}

	public function editUser(){
		$post = input('post.');
		$validate = Loader::validate('CheckAddUser');
		if(!$validate->scene('pass')->check($post)){
			$this->error($validate->getError());
		}
		$res = UserModel::where('user_id',$post['userId'])->update(['password'=>md5($post['password'])]);
		if ($res){
			$this->success('更改成功');
		}else{
			$this->error('更改失败,请稍后在试');
		}
	}


	public function editStatic(){
		$post = input('post.');
		if ($post['title']=='启用'){
			$res = UserModel::where(['user_id'=>$post['user_id']])->update(['static'=>0]);
			if ($res){
				$this->success('已启用');
			}else{
				$this->error('启用失败,请稍后再试');
			}
		}else{
			$res = UserModel::where(['user_id'=>$post['user_id']])->update(['static'=>1]);
			if ($res){
				$this->success('已禁用');
			}else{
				$this->error('禁用失败,请稍后再试');
			}
		}
	}
}